package com.ja.openchat.ui.found;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityCircleHomeBinding;
import com.ja.openchat.ui.base.BaseFragmentPagerAdapter;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.me.MyAlbumFragment;
import com.ja.openchat.views.QBadgeView;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.MediaInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.MediaStoreCompat;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.utils.KLog;
import q.rorbin.badgeview.Badge;

public class CircleHomeActivity extends JaBaseActivity<ActivityCircleHomeBinding, BaseViewModel> implements PostCircleMediaCallback , OnCirclePagerListener {

    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.postCircleStatusView)
    View postCircleStatusView;
    @BindView(R.id.postCircleStatus)
    TextView postCircleStatus;
    @BindView(R.id.postCircleProgress)
    ProgressBar postCircleProgress;
    @BindView(R.id.closePostCirlceBtn)
    View closePostCirlceBtn;
    ActivityCircleHomeBinding mBinding;

    private int currentIndex = 0;

    private MediaStoreCompat mediaStoreCompat;
    QBadgeView qBadgeView;
    private List<Fragment> mFragments;
    private List<String> titlePager;

    @Override
    public void initView() {
        super.initView();
        mBinding = (ActivityCircleHomeBinding) binding;
        qBadgeView = new QBadgeView(this);
        qBadgeView.setBadgeTextSize(9, true);
        qBadgeView.setGravityOffset(5, 5, true);
        qBadgeView.bindTarget(mBinding.headerImageViewRight).setBadgePadding(6, true)
                .setShowShadow(false)
                .setBadgeGravity(Gravity.TOP | Gravity.END)
                .setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                    }
                });
    }

    @Override
    public int getCurrentIndex() {
        return currentIndex;
    }

    @Override
    public void initData() {
        mFragments = pagerFragment();
        titlePager = pagerTitleString();
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.headerImageViewRight.setOnClickListener(v -> {
            startContainerActivity(MyAlbumFragment.class.getCanonicalName());
        });
        mBinding.headerImageViewRight.showUser(UserInfo.getUserInfo());
        mBinding.ivTakePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sendingBlogInfo != null) {
                    ToastUtils.showShort(getString(R.string.post_updating_later_try));
                    return;
                }
                if (mediaStoreCompat == null) {
                    mediaStoreCompat = new MediaStoreCompat(CircleHomeActivity.this);
                }
                PostCircleActivity.choosePostCircleMedia(mediaStoreCompat, CircleHomeActivity.this);
            }
        });
        BaseFragmentPagerAdapter pagerAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(), mFragments, titlePager);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(mFragments.size());
        mBinding.tabs.setupWithViewPager(mBinding.viewPager);
        mBinding.viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mBinding.tabs));
        mBinding.tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentIndex = tab.getPosition();
                KLog.d("currentIndex==" + currentIndex);
                updateTabView(tab, true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                updateTabView(tab, false);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        initTabs();
        loadUnReadInfo();

//        TelegramManager.getTelegramManager().getSendingBlogs(this, new TgResultBlock<BlogListInfo>() {
//            @Override
//            public void onResult(Map<String, Object> request, JsonObject response, BlogListInfo obj) {
//                if (obj != null && !Common.isEmpty(obj.blogs)) {
//                    sendingBlogInfo = obj.blogs.get(0);
//                    loadSendingBlogInfo();
//                }
//            }
//
//            @Override
//            public void onTimeout(Map<String, Object> request) {
//
//            }
//        });
    }

    void initTabs() {
        for (int i = 0; i < mBinding.tabs.getTabCount(); i++) {
            mBinding.tabs.getTabAt(i).setCustomView(getTabView(i));
        }
        if (mBinding.tabs.getTabCount() > 0)
            updateTabView(mBinding.tabs.getTabAt(0), true);
    }

    private View getTabView(int currentPosition) {
        View view = LayoutInflater.from(this).inflate(R.layout.red_packet_tab_item, null);
        TextView textView = (TextView) view.findViewById(R.id.tab_item_textview);
        textView.setText(titlePager.get(currentPosition));
        return view;
    }

    private void updateTabView(TabLayout.Tab tab, boolean isSelect) {
        if (isSelect) {
            //选中加粗
            TextView tabSelect = (TextView) tab.getCustomView().findViewById(R.id.tab_item_textview);
            tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tabSelect.setTextSize(24);
            tabSelect.setTextColor(getResources().getColor(R.color.color_text));
            tabSelect.setText(tab.getText());
        } else {
            TextView tabUnSelect = (TextView) tab.getCustomView().findViewById(R.id.tab_item_textview);
            tabUnSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tabUnSelect.setTextSize(16);
            tabUnSelect.setTextColor(getResources().getColor(R.color.color_text));
            tabUnSelect.setText(tab.getText());
        }
    }

    protected List<Fragment> pagerFragment() {
        List<Fragment> list = new ArrayList<>();
        //list.add(CircleHomeFragment.newInstance(0));
        list.add(CircleHomeFragment.newInstance(1));
        list.add(CircleHomeFragment.newInstance(2));
        return list;
    }

    protected List<String> pagerTitleString() {
        List<String> list = new ArrayList<>();
        //list.add(getString(R.string.popular_text));
        list.add(getString(R.string.unfocus_text));
        list.add(getString(R.string.friend_text));
        return list;
    }

    @Override
    protected void onResume() {
        super.onResume();
        TelegramManager.getTelegramManager().getCircleUnreadCount();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        PostCircleActivity.onActivityResultForPostCircleMedia(mediaStoreCompat, CircleHomeActivity.this, requestCode, resultCode, data, CircleHomeActivity.this);
    }

    @Override
    public void onSuccess(ArrayList<MediaInfo> mediaInfos) {
        if (mediaInfos != null && mediaInfos.size() > 0) {
            PostCircleActivity.startActivity(this, mediaInfos);
        }
    }

    private void loadUnReadInfo() {
        int count = TelegramManager.getTelegramManager().mCircleUnreadCount;
        qBadgeView.setBadgeNumber(count);
    }

    @Override
    public void onCancle() {

    }

    private void loadSendingBlogInfo() {
        if (sendingBlogInfo == null) {
            return;
        }
        postCircleStatusView.setVisibility(View.VISIBLE);
        postCircleStatusView.setClickable(false);
        mBinding.headerImageView.showUser(UserInfo.getUserInfo());
        postCircleStatus.setText(getString(R.string.publishing_text));
        postCircleStatus.setTextColor(getResources().getColor(R.color.me_nick_name_color_text_sub));
        postCircleStatus.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null);
        postCircleProgress.setProgress(0);
        closePostCirlceBtn.setVisibility(View.GONE);
    }


    private void loadSendingBlogInfoProgressingStatus() {
        if (sendingBlogInfo == null) {
            return;
        }
        if (postCircleStatusView.getVisibility() != View.VISIBLE) {
            loadSendingBlogInfo();
        }
        postCircleProgress.setProgress((int) Math.ceil(sendingBlogInfo.getUploadingRate() * 100));
    }


    private void loadSendingBlogInfoErrorStatus() {
        if (sendingBlogInfo == null) {
            return;
        }
        if (postCircleStatusView.getVisibility() != View.VISIBLE) {
            loadSendingBlogInfo();
        }
        postCircleStatusView.setClickable(true);
        postCircleStatus.setText(getString(R.string.post_faild_text));
        postCircleStatus.setTextColor(getResources().getColor(R.color.color_fd4e57));
        postCircleStatus.setCompoundDrawablesRelativeWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.post_circle_error_icon), null, null, null);
        postCircleProgress.setProgress(0);
        closePostCirlceBtn.setVisibility(View.VISIBLE);
        closePostCirlceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postCircleStatusView.setVisibility(View.GONE);
            }
        });
        postCircleStatusView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgress();
                TelegramManager.getTelegramManager().resendBlog(CircleHomeActivity.this, sendingBlogInfo.id, new TgResultBlock<TgResponse>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        hideProgress();
                        if (obj.ok) {
                            ToastUtils.showShort(getString(R.string.republished_post_success));
                            loadSendingBlogInfo();
                        } else {
                            showErrorTip(obj.errString);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        hideProgress();
                        showErrorTip(getString(R.string.request_error));
                    }
                });
            }
        });
    }

    private void loadSendingBlogInfoSuccessStatus() {
        sendingBlogInfo = null;
        postCircleStatusView.setVisibility(View.GONE);
    }


    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    private BlogInfo sendingBlogInfo;

    @Override
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null) {
            return;
        }
        switch (tg_event.event) {
            case EUser_Td_update_Circle_Unread_count:
                loadUnReadInfo();
                break;
            case ECircle_Send_Blog_Start:
                if (tg_event.data != null && tg_event.data instanceof BlogInfo) {
                    sendingBlogInfo = (BlogInfo) tg_event.data;
                    loadSendingBlogInfo();
                }
                break;
            case ECircle_Send_Blog_Progressing:
                if (tg_event.data != null && tg_event.data instanceof FileInfo) {
                    if (sendingBlogInfo != null) {
                        FileInfo fileInfo = (FileInfo) tg_event.data;
                        boolean isUpdate = sendingBlogInfo.updateFileInfo(fileInfo);
                        if (isUpdate) {
                            loadSendingBlogInfoProgressingStatus();
                        }
                    }
                }
                break;
            case ECircle_Send_Blog_Success:
                if (tg_event.data != null && tg_event.data instanceof BlogInfo && tg_event.dataEx instanceof Long) {
                    long oldBlogId = (Long) tg_event.dataEx;
                    BlogInfo blogInfo = (BlogInfo) tg_event.data;
                    if (sendingBlogInfo != null && oldBlogId == sendingBlogInfo.id) {
                        loadSendingBlogInfoSuccessStatus();
                    }
                }

                break;
            case ECircle_Send_Blog_Fail:
                if (tg_event.data != null && tg_event.data instanceof Long) {
                    long oldBlogId = (Long) tg_event.data;
                    if (sendingBlogInfo != null && oldBlogId == sendingBlogInfo.id) {
                        loadSendingBlogInfoErrorStatus();
                    }
                }
                break;
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_circle_home;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
